package com.xiaoming.api;

import com.xaioming.service.EmailService;
import com.xiaoming.dao.CodeRepository;
import com.xiaoming.entity.Code;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.Random;

@RestController
public class CodeController {
    @Reference(timeout = 60000,retries = 0)
    private EmailService emailService;
    @Autowired
    private CodeRepository repository;

    @GetMapping("/create/{email}")
    @Transactional
    public boolean senEmail(@PathVariable("email") String email) throws Exception {
        String[] codes = {"0", "2", "3", "4", "5", "6", "7", "8", "9"};
        Random random = new Random();
        int i = 0;
        String content = "";
        while (i < 6) {
            int index = random.nextInt(9);
            content += codes[index];
            i++;
        }
        Code code = new Code();
        code.setCode(content);
        Long currentTimeMillis = System.currentTimeMillis();
        code.setCreatetime(new Date(currentTimeMillis));
        code.setEmail(email);
        code.setExpiretime(new Date(currentTimeMillis + 600000));
        repository.save(code);
        return emailService.sendMail(email, content);
    }
}
